package com.qianying.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.entity.ChinaArea;
import com.qianying.mapper.ChinaAreaMapper;
import com.qianying.service.ChinaAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ChinaAreaServiceImpl extends ServiceImpl<ChinaAreaMapper, ChinaArea> implements ChinaAreaService {

    @Autowired
    ChinaAreaMapper chinaAreaMapper;

    @Override
    public CommonResult<?> getAreaByIdOrProvinces(Long id) {
        List<ChinaArea> res;
        if (id == null) {
            // ID为空时，返回所有省份（level=1）
            res = chinaAreaMapper.selectByLevel(1);

        } else {
            // ID不为空时，返回对应区域
            res = chinaAreaMapper.selectByParentId(id);

        }
        if (res.isEmpty()) {
            return CommonResult.failed("查询到的结果是空的！");
        }
        return CommonResult.success(res, "查询成功");
    }

    @Override
    public Map<Long, String> IdToNameMap() {
        // 查询所有区域记录（省/市/区）
        List<ChinaArea> areas = chinaAreaMapper.selectList(null);

        // 处理空列表情况
        if (areas == null || areas.isEmpty()) {
            return new HashMap<>(0);
        }

        // 转换为ID-名称映射Map
        return areas.stream()
                .collect(Collectors.toMap(
                        ChinaArea::getId,        // 键：区域ID
                        ChinaArea::getName,  // 值：区域名称
                        (existing, replacement) -> existing  // 处理ID重复（保留第一条）
                ));
    }
}

